﻿using FluentValidation;
using FluentValidation.Validators;
using System;

namespace PMS.Web.Framework.Validators
{
    /// <summary>
    /// Decimal validator
    /// </summary>
    public class DecimalPropertyValidator<T, TProperty> : PropertyValidator<T, TProperty>
    {
        public override string Name => "DecimalPropertyValidator";

        private readonly decimal _maxValue;

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="maxValue">Maximum value</param>
        public DecimalPropertyValidator(decimal maxValue)
        {
            _maxValue = maxValue;
        }

        protected override string GetDefaultMessageTemplate(string errorCode)
            => "Decimal value is out of range";
        /// <summary>
        /// Is valid?
        /// </summary>
        /// <param name="context">Validation context</param>
        /// <returns>Result</returns>
        public override bool IsValid(ValidationContext<T> context, TProperty value)
        {
            //if (decimal.TryParse(context.PropertyValue.ToString(), out decimal value))
            var decVal = (decimal?)Convert.ChangeType(value, typeof(decimal?));
            if(decVal.HasValue)
                return Math.Round(decVal.Value, 3) < _maxValue;

            return false;
        }
    }

}
